package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.pj.wisdomlogistics.MyApplication;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.view.LinePathView;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class SignActivity extends BaseActivity implements BaseActivity.RequestPermission {

    @BindView(R.id.signView)
    LinePathView mSignView;
    @BindView(R.id.iv_select)
    ImageView mIvSelect;
    @BindView(R.id.iv_sign)
    ImageView mIvSign;
    @BindView(R.id.iv_checked)
    ImageView mIvChecked;

    private boolean isSelect = false;
    private int resultCode = 0;
    private RequestOptions options;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            luBan();
        }
    };


    private String[] permission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE , Manifest.permission.READ_EXTERNAL_STORAGE};

    @Override
    public void initView() {
        options = new RequestOptions()
                .centerCrop()
                .priority(Priority.HIGH);

        String className = getIntent().getStringExtra("class");

        if (TextUtils.isEmpty(MyApplication.user.getSignPath()) || TextUtils.equals(className, "MainActivity")) {
            mIvSelect.setVisibility(View.GONE);
            mIvSign.setVisibility(View.GONE);
        } else {
            Glide.with(this).load(MyApplication.user.getSignPath()).apply(options).into(mIvSign);
        }

        setRequestPermissionListener(this);

    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_sign;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }


    @OnClick({R.id.iv_back, R.id.iv_select, R.id.iv_sign, R.id.bt_clear, R.id.bt_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                final Intent mIntent = new Intent();
                mIntent.putExtra("path", "");
                setResult(resultCode, mIntent);
                ActivityManagerUtil.create().finishActivity(this);
                break;
            case R.id.iv_select:
            case R.id.iv_sign:
                isSelect = !isSelect;
                mIvSelect.setImageResource(!isSelect ? R.drawable.unselected : R.drawable.selected);
                if (isSelect) {
                    mIvChecked.setVisibility(View.VISIBLE);
                    mSignView.setVisibility(View.GONE);
                    Glide.with(this).load(MyApplication.user.getSignPath()).apply(options).into(mIvChecked);
                } else {
                    mIvChecked.setVisibility(View.GONE);
                    mSignView.setVisibility(View.VISIBLE);
                }

                break;
            case R.id.bt_clear:
                mSignView.clear();
                if (isSelect) {
                    mIvChecked.setVisibility(View.GONE);
                    mSignView.setVisibility(View.VISIBLE);
                }
                isSelect = false;
                mIvSelect.setImageResource(R.drawable.unselected);
                break;
            case R.id.bt_save:
                try {
                    if (isSelect) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                copyFile(MyApplication.signPath);
                            }
                        }).start();

                    } else {
                        if (!checkPermissions(permission)) {
                            requestSystemPermissions(permission, 101);
                        } else {
                            mSignView.save(MyApplication.signPath,
                                    false, 0);
                            luBan();
                        }
                    }
                } catch (Exception mE) {
                    mE.printStackTrace();
                }

                break;
        }
    }

    @Override
    public void onBackPressed() {
        Intent mIntent = new Intent();
        mIntent.putExtra("path", "");
        setResult(resultCode, mIntent);
        ActivityManagerUtil.create().finishActivity(this);
    }

    public void copyFile(String path) {
        try {
            URL url = null;
            url = new URL(MyApplication.user.getSignPath());
            Log.e("Tag" , "MyApplication.user.getSignPath():" + MyApplication.user.getSignPath());
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(path);
            int len = 0;
            byte[] b = new byte[1024];
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            is.close();
            fos.close();
        } catch (Exception mE) {
            mE.printStackTrace();
        }

        mHandler.sendEmptyMessage(0);
    }

    public void luBan() {

        List<String> imagePath = new ArrayList<>();
        imagePath.add(MyApplication.signPath);

        Luban.get(this)
                .loadFiles(imagePath)
                .putGear(Luban.THIRD_GEAR)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {

                    }

                    @Override
                    public void onSuccess(List<File> files) {
                        Intent mIntent = new Intent();
                        mIntent.putExtra("path", files.get(0).getAbsolutePath());
                        SignActivity.this.setResult(resultCode, mIntent);
                        ActivityManagerUtil.create().finishActivity();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("Tag" , e.getMessage());
                        Toast.makeText(SignActivity.this, "图片压缩失败", Toast.LENGTH_SHORT).show();
                    }
                }).compress();
    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 101) {
            if (!checkPermissions(permission)) {
                CustomToast.showToast(this, "您拒绝了相关权限的请求", 1000);
            } else {
                try {
                    mSignView.save(MyApplication.signPath,
                            false, 0);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                luBan();
            }
        }
    }
}
